import { asyncRoutes, constantRoutes, adminRoutes, principalRoutes, CustomerRoutes, generalRoutes } from '@/router'
import { getLuYou } from '@/utils/auth'
import Layout from '@/layout'
import store from '..'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export const filterAsyncRouter = (routers, time) => {
  const accessedRouters = []
  routers.forEach(router => {
    if (router.path) {
      const url = router.path
      const obj = {}
      obj.path = '/' + router.path
      obj.component = Layout
      obj.children = [{
        path: 'index',
        name: router.name,
        component: resolve => require([`@/webpage/${url}/index`], resolve),
        meta: { title: router.name, icon: 'dashboard' }
      }]
      accessedRouters.push(obj)
    }
  })
  return accessedRouters
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  async generateRoutes({ commit, rootState }, roles) {
    return new Promise(resolve => {
      let routes = []
      routes = asyncRoutes || []
      if (rootState.user.roles.includes('admin')) {
        let array = JSON.parse(getLuYou())
        array.shift()
        JSON.parse(getLuYou()).shift()
        routes = principalRoutes.concat(filterAsyncRouter(array))
      } else {
        if (getLuYou()) {
          routes = CustomerRoutes.concat(filterAsyncRouter(JSON.parse(getLuYou())))
        }
      }
      commit('SET_ROUTES', routes)
      resolve(routes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
